<template>
  <div class="system-config">
    <el-tabs v-model="activeTab" class="config-tabs">
      <el-tab-pane label="基础配置" name="basic">
        <el-card>
          <el-form
            ref="basicFormRef"
            :model="basicConfig"
            :rules="basicRules"
            label-width="120px"
          >
            <el-form-item label="系统名称" prop="systemName">
              <el-input v-model="basicConfig.systemName" placeholder="请输入系统名称" />
            </el-form-item>
            
            <el-form-item label="系统Logo">
              <el-upload
                class="avatar-uploader"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleLogoChange"
              >
                <img v-if="basicConfig.logo" :src="basicConfig.logo" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
            
            <el-form-item label="系统描述" prop="description">
              <el-input
                v-model="basicConfig.description"
                type="textarea"
                :rows="4"
                placeholder="请输入系统描述"
              />
            </el-form-item>
            
            <el-form-item label="联系邮箱" prop="contactEmail">
              <el-input v-model="basicConfig.contactEmail" placeholder="请输入联系邮箱" />
            </el-form-item>
            
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="basicConfig.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveBasicConfig" :loading="saveLoading">
                保存配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="功能配置" name="feature">
        <el-card>
          <el-form
            ref="featureFormRef"
            :model="featureConfig"
            :rules="featureRules"
            label-width="150px"
          >
            <el-form-item label="允许用户注册" prop="allowRegistration">
              <el-switch v-model="featureConfig.allowRegistration" />
            </el-form-item>
            
            <el-form-item label="启用邮箱验证" prop="enableEmailVerification">
              <el-switch v-model="featureConfig.enableEmailVerification" />
            </el-form-item>
            
            <el-form-item label="启用手机验证" prop="enablePhoneVerification">
              <el-switch v-model="featureConfig.enablePhoneVerification" />
            </el-form-item>
            
            <el-form-item label="默认会员等级" prop="defaultMemberLevel">
              <el-select v-model="featureConfig.defaultMemberLevel" placeholder="请选择默认会员等级">
                <el-option label="普通会员" value="basic" />
                <el-option label="黄金会员" value="gold" />
                <el-option label="钻石会员" value="diamond" />
                <el-option label="VIP会员" value="vip" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="最大登录尝试次数" prop="maxLoginAttempts">
              <el-input-number
                v-model="featureConfig.maxLoginAttempts"
                :min="1"
                :max="10"
                controls-position="right"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveFeatureConfig" :loading="saveLoading">
                保存配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="支付配置" name="payment">
        <el-card>
          <el-form
            ref="paymentFormRef"
            :model="paymentConfig"
            :rules="paymentRules"
            label-width="150px"
          >
            <el-form-item label="支付方式" prop="paymentMethods">
              <el-checkbox-group v-model="paymentConfig.paymentMethods">
                <el-checkbox label="alipay">支付宝</el-checkbox>
                <el-checkbox label="wechat">微信支付</el-checkbox>
                <el-checkbox label="bank">银行卡</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <el-form-item label="默认支付方式" prop="defaultPaymentMethod">
              <el-select v-model="paymentConfig.defaultPaymentMethod" placeholder="请选择默认支付方式">
                <el-option label="支付宝" value="alipay" />
                <el-option label="微信支付" value="wechat" />
                <el-option label="银行卡" value="bank" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="货币单位" prop="currency">
              <el-input v-model="paymentConfig.currency" placeholder="请输入货币单位" />
            </el-form-item>
            
            <el-form-item label="最小充值金额" prop="minRechargeAmount">
              <el-input-number
                v-model="paymentConfig.minRechargeAmount"
                :min="0"
                :step="1"
                controls-position="right"
                style="width: 200px"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="savePaymentConfig" :loading="saveLoading">
                保存配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="AI配置" name="ai">
        <el-card>
          <el-form
            ref="aiFormRef"
            :model="aiConfig"
            :rules="aiRules"
            label-width="150px"
          >
            <el-form-item label="AI服务提供商" prop="provider">
              <el-select v-model="aiConfig.provider" placeholder="请选择AI服务提供商">
                <el-option label="OpenAI" value="openai" />
                <el-option label="阿里云" value="aliyun" />
                <el-option label="腾讯云" value="tencent" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="API密钥" prop="apiKey">
              <el-input
                v-model="aiConfig.apiKey"
                type="password"
                placeholder="请输入API密钥"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="默认模型" prop="defaultModel">
              <el-input v-model="aiConfig.defaultModel" placeholder="请输入默认模型名称" />
            </el-form-item>
            
            <el-form-item label="最大Token数" prop="maxTokens">
              <el-input-number
                v-model="aiConfig.maxTokens"
                :min="1"
                :max="4096"
                controls-position="right"
                style="width: 200px"
              />
            </el-form-item>
            
            <el-form-item label="启用AI解释" prop="enableAiInterpretation">
              <el-switch v-model="aiConfig.enableAiInterpretation" />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveAiConfig" :loading="saveLoading">
                保存配置
              </el-button>
              <el-button @click="testAiConnection" :loading="testLoading" style="margin-left: 20px">
                测试连接
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useConfigStore } from '@/stores'

// 使用配置store
const configStore = useConfigStore()

// 活动标签页
const activeTab = ref('basic')

// 保存加载状态
const saveLoading = ref(false)
const testLoading = ref(false)

// 基础配置表单引用
const basicFormRef = ref()
const featureFormRef = ref()
const paymentFormRef = ref()
const aiFormRef = ref()

// 基础配置
const basicConfig = reactive({
  systemName: '',
  logo: '',
  description: '',
  contactEmail: '',
  contactPhone: ''
})

// 功能配置
const featureConfig = reactive({
  allowRegistration: true,
  enableEmailVerification: true,
  enablePhoneVerification: true,
  defaultMemberLevel: 'basic',
  maxLoginAttempts: 5
})

// 支付配置
const paymentConfig = reactive({
  paymentMethods: [],
  defaultPaymentMethod: '',
  currency: '',
  minRechargeAmount: 0
})

// AI配置
const aiConfig = reactive({
  provider: '',
  apiKey: '',
  defaultModel: '',
  maxTokens: 2048,
  enableAiInterpretation: true
})

// 加载状态
const loading = computed(() => configStore.loading)

// 基础配置验证规则
const basicRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ]
}

// 功能配置验证规则
const featureRules = {
  defaultMemberLevel: [
    { required: true, message: '请选择默认会员等级', trigger: 'change' }
  ],
  maxLoginAttempts: [
    { required: true, message: '请输入最大登录尝试次数', trigger: 'blur' }
  ]
}

// 支付配置验证规则
const paymentRules = {
  paymentMethods: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  defaultPaymentMethod: [
    { required: true, message: '请选择默认支付方式', trigger: 'change' }
  ],
  currency: [
    { required: true, message: '请输入货币单位', trigger: 'blur' }
  ],
  minRechargeAmount: [
    { required: true, message: '请输入最小充值金额', trigger: 'blur' }
  ]
}

// AI配置验证规则
const aiRules = {
  provider: [
    { required: true, message: '请选择AI服务提供商', trigger: 'change' }
  ],
  apiKey: [
    { required: true, message: '请输入API密钥', trigger: 'blur' }
  ],
  defaultModel: [
    { required: true, message: '请输入默认模型名称', trigger: 'blur' }
  ],
  maxTokens: [
    { required: true, message: '请输入最大Token数', trigger: 'blur' }
  ]
}

// 处理Logo上传
const handleLogoChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    basicConfig.logo = e.target.result
  }
  reader.readAsDataURL(file.raw)
}

// 保存基础配置
const saveBasicConfig = () => {
  if (!basicFormRef.value) return
  
  basicFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        await configStore.updateSystemConfig(basicConfig)
        ElMessage.success('基础配置保存成功')
      } catch (error) {
        ElMessage.error('基础配置保存失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 保存功能配置
const saveFeatureConfig = () => {
  if (!featureFormRef.value) return
  
  featureFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        await configStore.updateSystemConfig(featureConfig)
        ElMessage.success('功能配置保存成功')
      } catch (error) {
        ElMessage.error('功能配置保存失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 保存支付配置
const savePaymentConfig = () => {
  if (!paymentFormRef.value) return
  
  paymentFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        await configStore.updatePaymentConfig(paymentConfig)
        ElMessage.success('支付配置保存成功')
      } catch (error) {
        ElMessage.error('支付配置保存失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 保存AI配置
const saveAiConfig = () => {
  if (!aiFormRef.value) return
  
  aiFormRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        await configStore.updateAiConfig(aiConfig)
        ElMessage.success('AI配置保存成功')
      } catch (error) {
        ElMessage.error('AI配置保存失败')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 测试AI连接
const testAiConnection = async () => {
  testLoading.value = true
  
  try {
    await configStore.testAiConnection()
    ElMessage.success('AI服务连接测试成功')
  } catch (error) {
    ElMessage.error('AI服务连接测试失败')
  } finally {
    testLoading.value = false
  }
}

// 获取配置数据
const fetchConfigData = async () => {
  try {
    // 获取系统配置
    const systemResponse = await configStore.fetchSystemConfig()
    Object.assign(basicConfig, systemResponse.data.system || {})
    Object.assign(featureConfig, systemResponse.data.feature || {})
    
    // 获取支付配置
    const paymentResponse = await configStore.fetchPaymentConfig()
    Object.assign(paymentConfig, paymentResponse.data)
    
    // 获取AI配置
    const aiResponse = await configStore.fetchAiConfig()
    Object.assign(aiConfig, aiResponse.data)
  } catch (error) {
    ElMessage.error('获取配置数据失败')
  }
}

// 组件挂载后获取配置
onMounted(() => {
  fetchConfigData()
})
</script>

<style lang="scss" scoped>
.system-config {
  .config-tabs {
    :deep(.el-tabs__content) {
      padding: 20px 0;
    }
  }
  
  .avatar-uploader {
    .avatar {
      width: 120px;
      height: 120px;
      display: block;
      border-radius: 6px;
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      transition: var(--el-transition-duration-fast);
      
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }
}
</style>